<?php
/**
 * Created by PhpStorm.
 * User: 共赢岛
 * Date: 2023/12/25
 * Time: 10:44
 */

namespace App\Services\LifeCycle;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class UploadService
{
    /**
     * 上传base64图片到七牛云
     * @param base64url
     * @return \Illuminate\Http\JsonResponse
     */
    public static function base64Upload($base_url = '')
    {
        // 构建鉴权对象(配置文件中获取密钥)
        $accessKey = config('filesystems.disks.qiniu.access_key');
        $secretKey = config('filesystems.disks.qiniu.secret_key');
        $bucket = config('filesystems.disks.qiniu.bucket');
        $domain = config('filesystems.disks.qiniu.domains.default');
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();

        $match = preg_match('/^(data:\s*image\/(\w+);base64,)/', $base_url, $result);

        $type = $result[2];

        // 新文件名
        $key = 'code/'.date('YmdHis') . rand(10000, 99999) . '.' . $type;

        $base_url = str_replace($result[1], '', $base_url);
        $base_url = str_replace(' ', '+', $base_url);

        list($ret, $err) = $uploadMgr->put($token, $key, base64_decode($base_url));

        return $ret['key'];
    }
}